const express = require('express');
const app = express();

const request = require('request');
const bodyParser = require('body-parser');

//设置跨域访问
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type, Accept, requestRepeatId");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", " 3.2.1");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// // 使用bodyParser 中间件来解析
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

// POST 请求
app.post("/*", (req, res) => {
    let reqBody = req.body;
    let contentType = req.headers['content-type'];
    let isForm = contentType.indexOf('application/x-www-form-urlencoded') > -1;

    if (!reqBody.url) {
        if (JSON.stringify(reqBody).replace(/\\/g, '').indexOf('"url":') === -1) {
            return res.json({
                ERROR: 'url参数必填'
            })
        }

        try {
            let tempBody = '';
            for (let key in reqBody) {
                tempBody = key + reqBody[key];
            }
            isForm = false;
            reqBody = JSON.parse(tempBody);
        } catch (e) {
            return res.json({
                ERROR: '请求的格式错误'
            })
        }
    }


    const url = reqBody.url;
    const method = reqBody.method || 'get';
    const header = reqBody.header || { "Content-Type": "application/json" };
    const data = reqBody.body || {};

    for (let key in reqBody) {
        if (!reqBody.header) {
            if (key.indexOf('header') > -1) {
                const name = key.replace('header', '').replace('[', '').replace(']', '');
                header[name] = reqBody[key];
            }
        }

        if (!reqBody.body) {
            if (key.indexOf('body') > -1) {
                const name = key.replace('body', '').replace('[', '').replace(']', '');
                data[name] = reqBody[key];
            }
        }        
    }

    // 转调请求逻辑
    const postContentType = header['Content-Type'] || 'application/json; charset=UTF-8';

    if (method.toLocaleLowerCase() === 'post') {
        
        request({
            url: url,
            method: "POST",
            headers: header,
            form: typeof(data) === 'string' ? JSON.parse(data) : data,
        }, function (err, dataRes) {
            if (err) {
                return res.json({
                    ERROR: err
                });
            }

            if (typeof dataRes.body === 'string') {
                try {
                    return res.json(JSON.parse(dataRes.body));
                } catch (error) {
                    return res.json({
                        ERROR: '调用失败，请检查传入的参数'
                    });
                }
            } else {
                return res.json(dataRes.body);
            }
        })

    } else {
        request({
            url,
            headers: header,
            qs: typeof(data) === 'string' ? JSON.parse(data || '{}') : data,
            // encoding: null //设置encoding
        }, (err, dataRes) => {
            if (err) {
                return res.json({
                    ERROR: err
                });
            }

            if (typeof dataRes.body === 'string') {
                try {
                    return res.json(JSON.parse(dataRes.body));
                } catch (error) {
                    return res.json({
                        ERROR: '调用失败，请检查传入的参数'
                    });
                }
            } else {
                return res.json(dataRes.body);
            }
        })
    }
});


app.listen(9001, () => {
    console.log('9001端口已启动');
})